package com.jy.appmarket.activity;

import com.jy.appmarket.R;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.CheckVerifyCodeNetEngine;
import com.jy.appmarket.network.engine.GetVerifyCodeNetEngine;
import com.jy.appmarket.network.resultdata.CheckVerifyCodeResult;
import com.jy.appmarket.network.resultdata.GetVerifyCodeResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.umeng.analytics.MobclickAgent;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CheckVerifyCodeActivity extends Activity implements OnClickListener, NetTaskListener{
	public static final String EXTRA_NAME = "name";
	public static final String EXTRA_PHONE_NUM = "phone_num";
	public static final String EXTRA_TYPE = "type";
	public static final String EXTRA_NEED_GET_VERIFY_CODE = "need_get_verify_code";
	
	public static final int TIMER_EXECUTE = 0x01;
	
	private NetTask mNetTask;
	private NetTask mNetTask2;
	private EditText mVerifyCodeEdit;
	private Button mSendVerifyCodeBtn;
	private WaitDialog mWaitDialog;
	
	private String mName;
	private String mPhoneNum;
	private String mType;
	private String mVerifyCode;
	private boolean mIsNeedGetVerifyCode;
	private int mVerifyCodeInterval;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TIMER_EXECUTE:
				refreshUI();
				break;

			default:
				break;
			}
		}
    };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_check_verify_code);
		
		getExtras();
		initTitle();
		initViews();
	}

	private void getExtras() {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				mName = extras.getString(EXTRA_NAME);
				mPhoneNum = extras.getString(EXTRA_PHONE_NUM);
				mType = extras.getString(EXTRA_TYPE);
				mIsNeedGetVerifyCode = extras.getBoolean(EXTRA_NEED_GET_VERIFY_CODE, false);
			}
		}
	}
	
	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(mName);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initViews() {
		mVerifyCodeEdit = findViewById(R.id.verify_code_edit);
		mSendVerifyCodeBtn = findViewById(R.id.send_verify_code_btn);
		mSendVerifyCodeBtn.setOnClickListener(this);
		
		if(mIsNeedGetVerifyCode) {
			mVerifyCodeInterval = 0;
			mSendVerifyCodeBtn.setBackgroundResource(R.drawable.download_button_blue);
			mSendVerifyCodeBtn.setEnabled(true); 
			mSendVerifyCodeBtn.setText(R.string.send_verify_code);
		} else {
			mVerifyCodeInterval = 60;
			mSendVerifyCodeBtn.setEnabled(false);
			mSendVerifyCodeBtn.setBackgroundResource(R.drawable.download_button_gray);
			mSendVerifyCodeBtn.setText(mVerifyCodeInterval+"秒后重发");
			Message msg = mHandler.obtainMessage();
			msg.what = TIMER_EXECUTE;
			mHandler.sendMessageDelayed(msg, 1000);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send_verify_code_btn:
			getVerifyCode();
			break;
		default:
			break;
		}
	}
	
	private void getVerifyCode() {
		mVerifyCodeInterval = 60;
		mSendVerifyCodeBtn.setEnabled(false);
		mSendVerifyCodeBtn.setBackgroundResource(R.drawable.download_button_gray);
		mSendVerifyCodeBtn.setText(mVerifyCodeInterval+"秒后重发");
		Message msg = mHandler.obtainMessage();
		msg.what = TIMER_EXECUTE;
		mHandler.sendMessageDelayed(msg, 1000);
		
		GetVerifyCodeNetEngine engine = new GetVerifyCodeNetEngine(mPhoneNum, mType);
		mNetTask = new NetTask(this, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}
	
	private void checkVerifyCode() {
		mVerifyCode = mVerifyCodeEdit.getText().toString().trim();

		if (TextUtils.isEmpty(mVerifyCode)) {
			Toast.makeText(this, R.string.please_input_verify_code,
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		showWaitDialog();
		CheckVerifyCodeNetEngine engine = new CheckVerifyCodeNetEngine(mPhoneNum, mType, mVerifyCode);
		mNetTask2 = new NetTask(this, engine, 1);
		mNetTask2.setListener(this);
		new Thread(mNetTask2).start();
	}
	
	public void refreshUI(){
		if(mVerifyCodeInterval > 0){
			mVerifyCodeInterval--;
			mSendVerifyCodeBtn.setText(mVerifyCodeInterval+"秒后重发");
			Message msg = mHandler.obtainMessage();
			msg.what = TIMER_EXECUTE;
			mHandler.sendMessageDelayed(msg, 1000);
		}else{
			mSendVerifyCodeBtn.setBackgroundResource(R.drawable.download_button_blue);
			mSendVerifyCodeBtn.setEnabled(true); 
			mSendVerifyCodeBtn.setText(R.string.send_verify_code);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.register_menu, menu);
		final MenuItem item = menu.findItem(R.id.action_next);
		item.setTitle(R.string.next);
		LinearLayout itemLayout = (LinearLayout) item.getActionView();
		TextView title = itemLayout.findViewById(R.id.menu_title);
		title.setText(R.string.next);
		
		itemLayout.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 CheckVerifyCodeActivity.this.onOptionsItemSelected(item);
             }
         });
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.action_next:
			checkVerifyCode();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		if (tag == 0) {
			GetVerifyCodeResult resultData = (GetVerifyCodeResult) engine.getResultData();
			if (!resultData.isOK()) {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, R.string.get_verify_code_error, Toast.LENGTH_SHORT).show();
				}
				mVerifyCodeInterval = 0;
			} else {
				Toast.makeText(this, R.string.get_verify_code_success, Toast.LENGTH_SHORT).show();
			}
		} else if (tag == 1) {
			dismissWaitDialog();
			CheckVerifyCodeResult resultData = (CheckVerifyCodeResult) engine.getResultData();
			if (!resultData.isOK()) {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, R.string.check_verify_code_error, Toast.LENGTH_SHORT).show();
				}
			} else {
				Intent intent = new Intent(this, SetPasswdActivity.class);
				Bundle bundle = new Bundle();
				if ("register".equals(mType)) {
					bundle.putString(SetPasswdActivity.EXTRA_NAME, "设置密码（2/3）");
					bundle.putString(SetPasswdActivity.EXTRA_TYPE, "register");
				} else if ("bind_phonenum".equals(mType)) {
					bundle.putString(SetPasswdActivity.EXTRA_NAME, "设置密码（3/3）");
					bundle.putString(SetPasswdActivity.EXTRA_TYPE, "bind_phonenum");
				}
				bundle.putString(SetPasswdActivity.EXTRA_PHONE_NUM, mPhoneNum);
				bundle.putString(SetPasswdActivity.EXTRA_VERIFY_CODE, mVerifyCode);
				intent.putExtras(bundle);
				startActivity(intent);
				finish();
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		dismissWaitDialog();
		if (tag == 0) {
			mVerifyCodeInterval = 0;
		}
		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		dismissWaitDialog();
	}
	
	private void showWaitDialog(){
		if (mWaitDialog == null) {
			mWaitDialog = new WaitDialog(this);
			mWaitDialog.setCanceledOnTouchOutside(false);
			mWaitDialog.setCancelable(false);
		}
		if (mWaitDialog.isShowing()) {
			return;
		}
		mWaitDialog.showTitle("请稍候...").show();
	}
	
	private void dismissWaitDialog(){
		if (mWaitDialog != null) {
			mWaitDialog.dismiss();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		if (mNetTask2 != null) {
			mNetTask2.cancel();
			mNetTask2.setListener(null);
			mNetTask2 = null;
		}
		dismissWaitDialog();
		super.onDestroy();
	}
}
